import { showMessage } from '@/components/antd-comp/message'
import ThemeBtn from '@/components/antd-comp/theme-btn'
import { getPublicKeyApi, getRolesApi } from '@/controllers/API/user'
import { useFuncsStore } from '@/store/funcStore'
import { useBuriedEvent } from '@/util/buried'
import { Button, Input, Modal, Select } from 'antd'
import { JSEncrypt } from 'jsencrypt'
import { useEffect, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { UserAdd, UserEdit, UserNameCheck, getEnterpriseApi } from '../API'
import './style/index.less'

const UserEditDia = ({ open, setOpen, obj, submitData }) => {
  /**
   * 功能权限限制
   */
  const { hasFuncPermission } = useFuncsStore()
  // ------埋点------
  const { UserBuriedEvent } = useBuriedEvent()
  /* 取消 */
  const handleCancel = (e: React.MouseEvent<HTMLElement>) => {
    setOpen(false)
  }
  /* dialog内容 */
  const [person, setPerson] = useState({
    user_name: '',
    enterprise_code: '',
    role_code: '',
    id: '',
    password: ''
  })
  // 角色
  const [standingList, setStandingList] = useState([])
  const [EnterpriseList, setEnterpriseList] = useState([])
  const { t } = useTranslation()
  // State for errors
  const [errors, setErrors] = useState<any>({})
  useEffect(() => {
    /* 角色 */
    getRolesApi().then((res: any) => {
      if (res?.list?.length > 0) {
        setStandingList(res.list)
      }
    })
    // 企业
    getEnterpriseApi().then(res => {
      if (res.data.length > 0) {
        setEnterpriseList(res.data)
      }
    })
    setPerson({
      ...person,
      ...obj
    })
  }, [])
  /* 提示报信信息 */
  const [error, setError] = useState({ user_name: false, role_code: false, enterprise_code: false, password: false })

  const close = () => {
    setOpen(false)
    submitData()
  }
  const handleEncrypt = async pwd => {
    const { public_key } = await getPublicKeyApi()
    const encrypt = new JSEncrypt()
    encrypt.setPublicKey(public_key)
    return encrypt.encrypt(pwd) as string
  }
  const checkName = async user_name => {
    const { is_exist } = (await UserNameCheck({ user_name })) as any
    return !is_exist
  }
  /* 密码正则 */
  const passwordRegex = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d!@#$%^&*]{8,}$/
  /* 提交表单 */
  const handleCreate = async () => {
    const isValid = validateForm()
    if (isValid) {
      if (!passwordRegex.test(person.password) && !person.id) {
        setErrors(prev => ({
          ...prev,
          password: '密码必须至少包含一个小写字母、一个大写字母、一个数字，并且长度不少于8个字符'
        }))
        return
      }
      let encryptPwd = ''
      let checkUserName = true
      if (!person.id) {
        encryptPwd = await handleEncrypt(person.password)
        checkUserName = await checkName(person.user_name)
      }
      if (!checkUserName) {
        showMessage({
          content: '用户名已存在',
          type: 'warning'
        })
        return
      }
      // if()
      const obj = {
        enterprise_code: person.enterprise_code,
        role_code: person.role_code,
        password: encryptPwd,
        // user_id: person.id,
        user_name: person.user_name
      }
      const buriedInfo = {
        page: person.id ? '编辑用户管理弹窗' : '创建用户管理弹窗',
        event_name: '【确定】按钮',
        data_id: person.id
      }
      if (person.id) {
        UserEdit({
          ...obj
        })
          .then((res: any) => {
            UserBuriedEvent({ ...buriedInfo })
            close()

            showMessage({
              content: '修改成功',
              type: 'success'
            })
          })
          .catch(() => {
            UserBuriedEvent({ ...buriedInfo })
          })
      } else {
        UserAdd({
          ...obj
        })
          .then((res: any) => {
            UserBuriedEvent({ ...buriedInfo })
            close()
            showMessage({
              content: '新增成功',
              type: 'success'
            })
          })
          .catch(() => {
            UserBuriedEvent({ ...buriedInfo })
          })
      }
    }
  }
  // Validate form fields
  const validateField = (name, value) => {
    switch (name) {
      case 'user_name':
        if (!value) return '用户名不可为空'
        if (value.length > 50) return '最多50个字符'
        return ''
      case 'role_code':
        if (!value) return '角色不可为空'
        return ''
      case 'enterprise_code':
        if (!value) return '企业不可为空'
        return ''
      case 'password':
        if (!value && !person.id) return '密码不可为空'
        return ''
      default:
        return ''
    }
  }
  // Handle field change
  const handleChange = (e, type) => {
    const error = validateField(type, e)
    setErrors(prev => ({ ...prev, [type]: error }))
    if (type === 'user_name') {
      setPerson({ ...person, user_name: e })
    } else if (type === 'password') {
      setPerson({ ...person, password: e })
    } else if (type === 'role_code') {
      setPerson({ ...person, role_code: e })
    } else if (type === 'enterprise_code') {
      setPerson({ ...person, enterprise_code: e })
    }
  }
  // Validate entire form
  const validateForm = () => {
    const formErrors = {}
    let isValid = true
    Object.keys(person).forEach(key => {
      const error = validateField(key, person[key])
      if (error) {
        formErrors[key] = error
        isValid = false
      }
    })
    setErrors(formErrors)
    return isValid
  }
  return (
    <>
      <Modal
        width={825}
        className="modal_antcomp_case max-h-[40%]"
        title={person.id ? '编辑' : '新增'}
        open={open}
        style={{ top: '10%' }}
        onCancel={handleCancel}
        maskClosable={false}
        footer={[
          <Button
            key="cancel"
            className="closeBtnStyles closeBtnWid"
            shape="round"
            onClick={() => {
              UserBuriedEvent({
                page: person.id ? '编辑用户管理弹窗' : '创建用户管理弹窗',
                event_name: '【取消】按钮'
              })
              setOpen(false)
            }}
          >
            {t('cancel')}
          </Button>,
          <ThemeBtn key="create" className="closeBtnWid" onClick={() => handleCreate()}>
            确认
          </ThemeBtn>
        ]}
      >
        <div
          style={{ overflowY: 'scroll', height: '430px' }}
          className="caseOverFlowY flex flex-col gap-4 py-2 pr-1 sm:max-w-[825px]"
        >
          {/* 名称 */}
          <div className="">
            <label htmlFor="name" className="bisheng-label labelSizePort">
              用户名
              <span className="bisheng-tip">*</span>
            </label>
            <Input
              name="user_name"
              autoComplete="off"
              value={person.user_name}
              disabled={!!person.id}
              onChange={e => handleChange(e.target.value, 'user_name')}
              placeholder="用户名"
              className={`col-span-3 ${error.user_name && 'border-red-400'} contMarginTop inoutHig`}
            />
            {errors.user_name && <p className="bisheng-tip mt-1">{errors.user_name}</p>}
          </div>
          {/* 角色 */}
          <div className="">
            <label htmlFor="name" className="bisheng-label labelSizePort">
              角色
              <span className="bisheng-tip">*</span>
            </label>
            <Select
              key={'role_code'}
              className={`col-span-3 ${error.role_code && 'border-red-400'} contMarginTop inoutHig`}
              placeholder="角色"
              value={person.role_code ? person.role_code : null}
              style={{ width: '100%' }}
              onChange={val => handleChange(val, 'role_code')}
              options={standingList}
              fieldNames={{ label: 'name', value: 'code' }}
            />
            {errors.role_code && <p className="bisheng-tip mt-1">{errors.role_code}</p>}
          </div>
          {/* 企业 */}
          <div className="">
            <label htmlFor="name" className="bisheng-label labelSizePort">
              企业
              <span className="bisheng-tip">*</span>
            </label>
            <Select
              key={'enterprise_code'}
              className={`col-span-3 ${error.enterprise_code && 'border-red-400'} contMarginTop inoutHig`}
              placeholder="企业"
              value={person.enterprise_code ? person.enterprise_code : null}
              style={{ width: '100%' }}
              onChange={val => handleChange(val, 'enterprise_code')}
              options={EnterpriseList}
              fieldNames={{ label: 'name', value: 'code' }}
            />
            {errors.enterprise_code && <p className="bisheng-tip mt-1">{errors.enterprise_code}</p>}
          </div>
          {/* 密码 */}
          {!person.id && (
            <div className="">
              <label htmlFor="name" className="bisheng-label labelSizePort">
                密码
                <span className="bisheng-tip">*</span>
              </label>
              <Input
                name="password"
                autoComplete="off"
                value={person.password}
                onChange={e => handleChange(e.target.value, 'password')}
                placeholder="密码"
                className={`col-span-3 ${error.password && 'border-red-400'} contMarginTop inoutHig`}
              />
              {errors.password && <p className="bisheng-tip mt-1">{errors.password}</p>}
            </div>
          )}
        </div>
      </Modal>
    </>
  )
}

export default UserEditDia
